import React, { useState, useEffect } from 'react';
import { Tabs } from 'antd';
import Editor from '@monaco-editor/react';
import styles from './TemplateEditor.module.css';

// 映射语言名称到Monaco编辑器的语言ID
const LANGUAGE_MAPPING: Record<string, string> = {
  'C': 'c',
  'C++': 'cpp',
  'Java': 'java',
  'Python3': 'python',
  'Golang': 'go',
  'JavaScript': 'javascript'
};

interface TemplateEditorProps {
  value?: Record<string, string>;
  onChange?: (value: Record<string, string>) => void;
  problemId?: string;
  selectedLanguages?: string[];
}

const TemplateEditor: React.FC<TemplateEditorProps> = ({ 
  value = {}, 
  onChange,
  problemId,
  selectedLanguages = []
}) => {
  const [activeKey, setActiveKey] = useState<string>('');

  // 当选中的语言改变时，更新活动语言
  useEffect(() => {
    if (selectedLanguages.length > 0 && (!activeKey || !selectedLanguages.includes(activeKey))) {
      setActiveKey(selectedLanguages[0]);
    }
  }, [selectedLanguages]);

  const handleCodeChange = (code: string | undefined) => {
    if (code !== undefined && onChange) {
      const newValue = { ...value, [activeKey]: code };
      onChange(newValue);
    }
  };

  const handleTabChange = (key: string) => {
    setActiveKey(key);
  };

  // 获取要显示的语言列表，根据selectedLanguages筛选
  const displayLanguages = selectedLanguages.length > 0 
    ? selectedLanguages
    : [];

  // 如果没有可显示的语言，返回空
  if (displayLanguages.length === 0) {
    return <div className={styles.emptyEditor}>请先选择题目支持的语言</div>;
  }

  return (
    <div className={styles.templateEditor}>
      <Tabs 
        activeKey={activeKey} 
        onChange={handleTabChange}
        items={displayLanguages.map(lang => ({
          key: lang,
          label: lang,
          children: (
            <Editor
              height="300px"
              value={value[lang] || ''}
              language={LANGUAGE_MAPPING[lang] || 'text'}
              onChange={handleCodeChange}
              theme="vs-light"
              options={{
                minimap: { enabled: false },
                scrollBeyondLastLine: false,
                fontSize: 14,
                tabSize: 4,
                wordWrap: 'on',
                lineNumbers: 'on',
                automaticLayout: true
              }}
            />
          )
        }))}
      />
    </div>
  );
};

export default TemplateEditor;
